package com.gz.service.impl;

import com.gz.dao.AnswersMapper;
import com.gz.dao.QuestionMapper;
import com.gz.dao.StudentQuestionTagWeightsMapper;
import com.gz.dto.*;
import com.gz.entity.*;
import com.gz.dao.UserAnswersMapper;
import com.gz.service.UserAnswersService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户答题结果详情表(UserAnswers)表服务实现类
 *
 * @author makejava
 * @since 2024-05-27 15:40:59
 */
@Service
public class UserAnswersServiceImpl implements UserAnswersService {
    @Autowired
    private UserAnswersMapper userAnswersDao;
    @Autowired
    private AnswersMapper answersDao;
    @Autowired
    private QuestionMapper questionDao;
    @Autowired
    private StudentQuestionTagWeightsMapper studentQuestionTagWeightsDao;
    @Value("${app.aiPaperQuestionCnt}")
    private String aiPaperQuestionCnt;
   @Value("${app.aiPaperTotalScore}")
     private String aiPaperTotalScore;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public UserAnswers queryById(Integer id) {
        return userAnswersDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @Override
    public PageData queryByPage(UserAnswersDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<UserAnswers> list = userAnswersDao.queryAll(dto);
        PageInfo<UserAnswers> pageInfo = new PageInfo<>(list);
        return new PageData<>(pageInfo.getTotal(), list);
    }

    /**
     * 条件查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @Override
    public List<UserAnswers> queryAll(UserAnswersDto dto) {
        List<UserAnswers> list = userAnswersDao.queryAll(dto);
        return list;
    }
    @Override
    public List<UserAnswers> queryRecentFault(RecentFaultDto recentFaultDto){
        List<UserAnswers> list = userAnswersDao.queryRecentSubjectFault(recentFaultDto);
        return list;
    }

    /**
     * 新增数据
     *
     * @param userAnswers 实例对象
     * @return 实例对象
     */
    @Override
    public UserAnswers insert(UserAnswers userAnswers) {
        userAnswersDao.insert(userAnswers);
        return userAnswers;
    }

    @Override
    @Transactional
    public int insertBatch(List<UserAnswers> entities) {
        /** 先交卷 */
        /** 如果后台处理对错 */
        /** 先拿到所有题目id查询题目的答案 */
        List<Integer> qIds = entities.stream().map(UserAnswers::getQuestionId).collect(Collectors.toList());
        QuestionDto param = new QuestionDto();
        param.setIds(qIds);
        int i = userAnswersDao.insertBatch(entities);
        /** 交卷更新交卷时间 */
        Answers updAnswer = new Answers();
        updAnswer.setAnswerId(entities.get(0).getAnswerId());
        updAnswer.setSubmitTime(new Date());
        answersDao.update(updAnswer);
        /** 处理权重 */
        this.handleWeights(entities);
        return i;
    }
    @Override
    public int handleWeights(List<UserAnswers> entities) {
        Answers answers = answersDao.queryById(entities.get(0).getAnswerId());
        /** 新增权重数据 */
        List<StudentQuestionTagWeights> addData= new ArrayList<>();
        /** 更新权重数据 */
        List<StudentQuestionTagWeights> updateData= new ArrayList<>();
        /** 先拿到用户所有权重留着 */
        List<StudentQuestionTagWeights> studentWeights = studentQuestionTagWeightsDao.queryByStId(answers.getUserId());
        List<Integer> userWeightLabelIds = studentWeights.stream().map(StudentQuestionTagWeights::getTag).collect(Collectors.toList());
        /** 如果后台处理对错 */
        /** 先拿到所有题目id查询题目的答案 */
        List<Integer> qIds = entities.stream().map(UserAnswers::getQuestionId).collect(Collectors.toList());
        QuestionDto param = new QuestionDto();
        param.setIds(qIds);
        List<Question> questions = questionDao.queryAll(param);
        /** 计算标签错误次数集合 */
       List<Integer> wrongTotalLabels = new ArrayList<>();
        for(UserAnswers ua:entities){
            /** 拿到作答题目对应的答案 */
            Question question = questions.stream().filter(j -> ua.getQuestionId() == j.getId()).findFirst().get();
            System.out.println("q->"+ua.getUserAnswer());
            System.out.println("a->"+question.getQuestionAnswer());
            /** 先判断是否答对，答错的话增加权重 */
                if(StringUtils.isNotEmpty(question.getQuestionAnswer())&&!ua.getUserAnswer().equalsIgnoreCase(question.getQuestionAnswer())){
                    ua.setIsCorrect(2);
                    List<Integer> wrongQuestionLabels = question.getLabels().stream().map(LabelInfo::getId).collect(Collectors.toList());
                    wrongTotalLabels.addAll(wrongQuestionLabels);

                }
        }
        /** 如果错题标签数据非空 */
        if (CollectionUtils.isNotEmpty(wrongTotalLabels)) {
            /** 把错题权重标签数据分组统计出现次数 */
            Map<Integer, Long> frequencyMap = wrongTotalLabels.stream()
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
            frequencyMap.forEach((key, value) -> {
                        StudentQuestionTagWeights stuWeightsParam = new StudentQuestionTagWeights();
                        stuWeightsParam.setStudentId(answers.getUserId());
                        stuWeightsParam.setTag(key);
                        /** 如果权重表原来就有数据 那么错题标签出线次数*2 + 原来权重数 */
                        if (userWeightLabelIds.contains(key)) {
                            StudentQuestionTagWeights studentQuestionTagWeights = studentWeights.stream().filter(k -> key == k.getTag()).findFirst().get();
                            stuWeightsParam.setErrorWeight(studentQuestionTagWeights.getErrorWeight() + (2 * value.intValue()));
                            updateData.add(stuWeightsParam);
                        } else {
                            /** 如果权重表原来没有数据 那么错题标签出线次数*2  */
                            stuWeightsParam.setErrorWeight(2 * value.intValue());
                            addData.add(stuWeightsParam);
                        }
                    }

            );
        }
        if(CollectionUtils.isNotEmpty(addData)){
            addData.stream().distinct().collect(Collectors.toList());
            studentQuestionTagWeightsDao.insertBatch(addData);
        }
        if(CollectionUtils.isNotEmpty(updateData)){
            updateData.stream().distinct().collect(Collectors.toList());
            studentQuestionTagWeightsDao.updateBatchSelective(updateData);
        }
        return addData.size()+updateData.size();
    }
    /**
     * 修改数据
     *
     * @param userAnswers 实例对象
     * @return 实例对象
     */
    @Override
    public UserAnswers update(UserAnswers userAnswers) {
        userAnswersDao.update(userAnswers);
        return queryById(userAnswers.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return userAnswersDao.deleteById(id) > 0;
    }
}
